package order

import (
	"context"
	"encoding/json"

	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"
	"laundry-service/entity"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetReservationOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetReservationOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetReservationOrderLogic {
	return &GetReservationOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetReservationOrderLogic) GetReservationOrder(req *types.GetReservationOrderReq) (resp *types.GetReservationOrderResp, err error) {
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()
	reservation, err := l.svcCtx.Db.FindReservationOrderByOrderId(req.OrderId)
	if err != nil {
		return nil, nil
	}

	pickupAddr, err := l.svcCtx.Db.FindAddrById(userId, reservation.PickupAddrId)
	if err != nil {
		return nil, nil
	}
	deliveryAddr, err := l.svcCtx.Db.FindAddrById(userId, reservation.DeliveryAddrId)
	if err != nil {
		return nil, nil
	}

	address := make([]types.CreateAddressResp, 2)
	for i, addr := range []*entity.Address{pickupAddr, deliveryAddr} {
		address[i] = types.CreateAddressResp{
			Id:         addr.ID,
			CreatedAt:  addr.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:  addr.UpdatedAt.Format("2006-01-02 15:04:05"),
			Region:     addr.Region,
			Detail:     addr.Detail,
			Phone:      addr.Phone,
			Name:       addr.Name,
			PostalCode: addr.PostalCode,
			Default:    addr.Default,
		}
	}

	return &types.GetReservationOrderResp{
		Id:              reservation.ID,
		OrderId:         reservation.OrderId,
		PickupAddr:      address[0],
		DeliveryAddr:    address[1],
		AppointmentTime: reservation.AppointmentTime,
		CreatedAt:       reservation.CreatedAt,
	}, nil
}
